package com.saoft.jcms.web.controller;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.saoft.jcms.entity.Archives;
import com.saoft.jcms.service.ArchivesService;
import com.saoft.jcms.web.dto.LayuiTableData;
import com.saoft.jcms.web.dto.ResponseDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("archives")
public class ArchivesController {

    @Autowired
    ArchivesService archivesService;

    @GetMapping("index")
    public String index(){
        return "archives/index";
    }

    @GetMapping("add")
    public String addPage(Model model){
        model.addAttribute("archives", new Archives());
        return "archives/add";
    }

    @GetMapping("edit")
    public String eidtPage(String id, Model model){
        Archives archives = archivesService.getById(id);
        model.addAttribute("archives", archives);
        return "archives/add";
    }

    @ResponseBody
    @PostMapping("save")
    public ResponseDTO save(Archives archives){
        if (StringUtils.hasLength(archives.getId())) {
            archivesService.updateById(archives);
        }else{
            String uuid = IdUtil.fastSimpleUUID();
            archives.setId(uuid);
            archivesService.save(archives);
        }

        return ResponseDTO.success();
    }

    @ResponseBody
    @PostMapping("delete")
    public ResponseDTO delete(String id){
        archivesService.removeById(id);
        return ResponseDTO.success();
    }

    @ResponseBody
    @GetMapping("list")
    public LayuiTableData list(Integer page, Integer limit) {
        Page query = new Page<Archives>();
        query.setCurrent(page);
        query.setSize(limit);
        Page page1 = archivesService.page(query);

        LayuiTableData tableData = new LayuiTableData();
        tableData.setCode(0);
        tableData.setData(page1.getRecords());
        tableData.setTotal(page1.getTotal());

        return tableData;
    }
}
